var timeout_json = function(data, $window) {
	if(data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if(ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch(e) {
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}

var changeCheck = function(e, isCheck) {
	var _ = $(e);
	if(isCheck == 0 || isCheck == 1) {
		if(isCheck == 0) {
			_.removeClass('checked');
		} else {
			_.addClass('checked');
		}
	} else {
		if(_.attr('class').search('checked') > -1) {
			_.removeClass('checked');
		} else {
			_.addClass('checked');
		}
	}
}

var app = angular.module("kwdEditApp", []),
	ifm_id = UI.getParameterByName('ifm_id'),
	groupIde = UI.getParameterByName('groupId'),
	opt_type;
app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});

app.controller('editCtrl', function($scope, $http, $window, $timeout) {
	$scope.matchFlag=false;
	$scope.filterFlag=false;
	var vm = $scope.vm = {
		ifm_id: null,
		ifm_name: null,
		ifm_pushed: 0,
		ifm_type: null,
		ifm_note: null,
		ifm_getChannel: null,
		ifm_notChannel: null,
		ifm_getWechatId: null,
		ifm_notWechatId: null,
		ifm_getBloggerId: null,
		ifm_notBloggerId: null,
		ifm_getBbsName: null,
		ifm_notBbsName: null,
		ifm_getKeyword: "",
		ifm_notKeyword: "",
		ifm_isdelete: null,
		ifm_matePattern: "",
		ifm_filterPattern: ""
	};

	$scope.domAjax = function(e) {
		var isPublished = $("#publish").attr("disabled");
		if(isPublished == "disabled"){
			return false;
		}		
		if((e === "release")) {
			//提交的匹配关键词-匹配（标题、正文）参数
			if(($("#match_title").attr("class").search("checked")>-1)&&($("#match_body").attr("class").search("checked")>-1)){
				$scope.vm.ifm_matePattern="title|content";
			}else if(($("#match_title").attr("class").search("checked")>-1)&&($("#match_body").attr("class").search("checked")==-1)){
				$scope.vm.ifm_matePattern="title";
			}else if(($("#match_title").attr("class").search("checked")==-1)&&($("#match_body").attr("class").search("checked")>-1)){
				$scope.vm.ifm_matePattern="content";
			}else{
				$scope.vm.ifm_matePattern=null;
			}
			//提交的过滤关键词-匹配（标题、正文）参数
			if(($("#match_title2").attr("class").search("checked")>-1)&&($("#match_body2").attr("class").search("checked")>-1)){
				$scope.vm.ifm_filterPattern="title|content";
			}else if(($("#match_title2").attr("class").search("checked")>-1)&&($("#match_body2").attr("class").search("checked")==-1)){
				$scope.vm.ifm_filterPattern="title";
			}else if(($("#match_title2").attr("class").search("checked")==-1)&&($("#match_body2").attr("class").search("checked")>-1)){
				$scope.vm.ifm_filterPattern="content";
			}else{
				$scope.vm.ifm_filterPattern=null;
			}
			var params = {
				ifm_id: $scope.vm.ifm_id,
				ifm_name: $scope.vm.ifm_name,
				ifm_pushed: $scope.vm.ifm_pushed,
				ifm_type: $scope.vm.ifm_type,
				ifm_note: $scope.vm.ifm_note,
				
				ifm_getChannel: $scope.vm.ifm_getChannel,
				ifm_notChannel: $scope.vm.ifm_notChannel,
				ifm_getWechatId: $scope.vm.ifm_getWechatId,
				ifm_notWechatId: $scope.vm.ifm_notWechatId,
				ifm_getBloggerId: $scope.vm.ifm_getBloggerId,
				ifm_notBloggerId: $scope.vm.ifm_notBloggerId,
				ifm_getBbsName: $scope.vm.ifm_getBbsName,
				ifm_notBbsName: $scope.vm.ifm_notBbsName,
				ifm_getKeyword: $scope.vm.ifm_getKeyword,
				ifm_notKeyword: $scope.vm.ifm_notKeyword,
				ifm_isdelete: $scope.vm.ifm_isdelete,
				ifm_matePattern: $scope.vm.ifm_matePattern,
				ifm_filterPattern: $scope.vm.ifm_filterPattern

			};
/*			//中文括号替换成英文括号
			if(params.ifm_getKeyword!=""&&params.ifm_getKeyword!=null){
				params.ifm_getKeyword = params.ifm_getKeyword.replace("（", "(").replace("）", ")");
				params.ifm_getKeyword = params.ifm_getKeyword;
			}else if(params.ifm_notKeyword!=""&&params.ifm_notKeyword!=null){
				params.ifm_notKeyword = params.ifm_notKeyword.replace("（", "(").replace("）", ")");
	        	params.ifm_notKeyword = params.ifm_notKeyword;
			}*/
			if(params.ifm_getKeyword==""){
				params.ifm_getKeyword="None";
			}
			if(params.ifm_notKeyword==""){
				params.ifm_notKeyword="None";
			}
        	//验证关键词的特殊字符
			var strReg = "^[\\u4e00-\\u9fa5a-zA-Z0-9+|()\\s\\\\]+$";
			var re = new RegExp(strReg);
			if(params.ifm_getKeyword!=undefined&&!re.test($.trim(params.ifm_getKeyword))) {
				layer.msg("匹配关键词含有非法字符",2,-1);
				return false;
			}else if(params.ifm_notKeyword!=undefined&&!re.test($.trim(params.ifm_notKeyword))) {
				layer.msg("过滤关键词含有非法字符",2,-1);
				return false;
			}
			if(params.ifm_getKeyword=="None"&&(vm.ifm_matePattern=="title"||vm.ifm_matePattern=="title|content"||vm.ifm_matePattern=="content")){
				layer.msg("请输入匹配关键词,或取消相应匹配标题或正文",3,-1);
				return false;
			}
			if(params.ifm_notKeyword=="None"&&(vm.ifm_filterPattern=="title"||vm.ifm_filterPattern=="title|content"||vm.ifm_filterPattern=="content")){
				layer.msg("请输入过滤关键词,或取消相应匹配标题或正文",3,-1);
				return false;
			}
			if(params.ifm_getKeyword!="None"&&(vm.ifm_matePattern==null)){
				layer.msg("请选择匹配关键词的匹配标题或正文",3,-1);
				return false;
			}
			if(params.ifm_notKeyword!="None"&&(vm.ifm_filterPattern==null)){
				layer.msg("请选择过滤关键词的匹配标题或正文",3,-1);
				return false;
			}
			
			if(params.ifm_getKeyword!=undefined&&params.ifm_notKeyword!=undefined){
				$.ajax({
					type: "POST",
					url: basePath + 'iformation/modifyIformation.do?discern=2',
					data: params,
					error: function(request) {
						layer.msg("操作失败，请刷新重试！", 2, -1);
					},
					success: function(data) {
						var j = timeout_json(data, $window);
						if(j == false) {
							return false;
						}
						if(data.returnCode == 10000) {
							layer.msg(data.returnMessage, 1, 10);
							//保存iframe窗口后，不跳转页面
							var t = setTimeout(function(){
								window.parent.$(".dtab").find('#jsgo a.cur').trigger('click');
								window.parent.layer.closeAll();
							},1000);
						} else {
							layer.msg(data.returnMessage, 2, -1);
							return false;
						}
					}
				});
			}
		}
	};
	
	//匹配过滤前的勾选框
	$scope.doCheckChange = function(e, isCheck) {
		changeCheck(e, isCheck);
	}
	$scope.cancel = function(e) {
		window.parent.layer.closeAll();
	}
	$scope.initData = function(e) {
		
		var isP_title = 0;
		var isP_content = 0;
		var isF_title = 0;
		var isF_content =0;
		//匹配标题
		if(vm.ifm_matePattern=="title"||vm.ifm_matePattern=="title|content") {
			isP_title = 1;
		}
		$scope.doCheckChange($("#match_title"), isP_title);
		//匹配正文
		if(vm.ifm_matePattern=="content"||vm.ifm_matePattern=="title|content") {
			isP_content = 1;
		}
		$scope.doCheckChange($("#match_body"), isP_content);
		
		//过滤标题
		if(vm.ifm_filterPattern=="title"||vm.ifm_filterPattern=="title|content") {
			isF_title = 1;
		}
		$scope.doCheckChange($("#match_title2"), isF_title);
		//过滤正文
		if(vm.ifm_filterPattern=="content"||vm.ifm_filterPattern=="title|content") {
			isF_content = 1;
		}
		$scope.doCheckChange($("#match_body2"), isF_content);
//		if($scope.vm.ifm_getKeyword=="None"){
//			$scope.vm.ifm_getKeyword="";
//		}
//		if($scope.vm.ifm_notKeyword=="None"){
//			$scope.vm.ifm_notKeyword="";
//		}
	}
	//查询数据初始化
	if(ifm_id != undefined) {
		opt_type = 1;
		$http.get(basePath + 'iformation/queryByID2.do?ifm_id=' + ifm_id + '&groupId=' + groupIde).success(function(data) {
			var j = timeout_json(data, $window);
			if(j == false) {
				return false;
			}
			if(data.returnCode == 10000) {
				vm = $scope.vm = data.returnData;
			}
			$scope.initData();
		});
	} else {
		opt_type = 0;
		$scope.initData();
	}
});

/**
 * 文本框根据输入内容自适应高度
 * @param   {HTMLElement} 	 输入框元素
 * @param   {Number}         设置光标与输入框保持的距离(默认0)
 * @param   {Number}         设置最大高度(可选)
 */
var autoTextarea = function (elem, extra, maxHeight) {
        extra = extra || 0;
        var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
        isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
                addEvent = function (type, callback) {
                        elem.addEventListener ?
                                elem.addEventListener(type, callback, false) :
                                elem.attachEvent('on' + type, callback);
                },
                getStyle = elem.currentStyle ? function (name) {
                        var val = elem.currentStyle[name];
                        if (name === 'height' && val.search(/px/i) !== 1) {
                                var rect = elem.getBoundingClientRect();
                                return rect.bottom - rect.top -
                                        parseFloat(getStyle('paddingTop')) -
                                        parseFloat(getStyle('paddingBottom')) + 'px';        
                        };
                        return val;
                } : function (name) {
                        return getComputedStyle(elem, null)[name];
                },
                minHeight = parseFloat(getStyle('height'));
        elem.style.resize = 'none';
        var change = function () {
                var scrollTop, height,
                        padding = 0,
                        style = elem.style;
                if (elem._length === elem.value.length) return;
                elem._length = elem.value.length;
                if (!isFirefox && !isOpera) {
                        padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
                };
                scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
                elem.style.height = minHeight + 'px';
                if (elem.scrollHeight > minHeight) {
                        if (maxHeight && elem.scrollHeight > maxHeight) {
                                height = maxHeight - padding;
                                style.overflowY = 'auto';
                        } else {
                                height = elem.scrollHeight - padding;
                                style.overflowY = 'hidden';
                        };
                        style.height = height + extra + 'px';
                        scrollTop += parseInt(style.height) - elem.currHeight;
                        document.body.scrollTop = scrollTop;
                        document.documentElement.scrollTop = scrollTop;
                        elem.currHeight = parseInt(style.height);
                };
        };
        addEvent('propertychange', change);
        addEvent('input', change);
        addEvent('focus', change);
        change();
};
var kwdText = document.getElementById("kwd");
var fwdText = document.getElementById("fwd");
autoTextarea(kwdText);
autoTextarea(fwdText);
